<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { fetchGoodCommentsList, replyGoodComments } from '@/api/goodCommentsApi'

const props = defineProps({
  dealerGoodsStoreId: {
    type: String,
    required: true,
  },
})

const loading = ref(false)
const commentList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const replyDialogVisible = ref(false)
const replyContent = ref('')
const replyLoading = ref(false)
const replyTarget = ref(null)

const openReplyDialog = (item) => {
  replyTarget.value = item
  replyContent.value = ''
  replyDialogVisible.value = true
}
const closeReplyDialog = () => {
  replyDialogVisible.value = false
  replyContent.value = ''
  replyTarget.value = null
}
const handleReplySubmit = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空')
    return
  }
  replyLoading.value = true
  try {
    const params = {
      ...replyTarget.value,
      replyEvaluate: replyContent.value,
      replyTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      editType: 1, // 1代表回复
    }
    const res = await replyGoodComments({
      ...params,
      editType: 1,
    })
    if (res.success) {
      ElMessage.success('回复成功')
      closeReplyDialog()
      fetchComments()
    } else {
      ElMessage.error(res.msg || '回复失败')
    }
  } catch (error) {
    logger.error('回复失败', error)
    ElMessage.error('回复失败')
  } finally {
    replyLoading.value = false
  }
}

const fetchComments = async () => {
  loading.value = true
  try {
    const res = await fetchGoodCommentsList({
      queryFields: {
        dealerGoodsStoreId: props.dealerGoodsStoreId,
      },
      currentPage: currentPage.value,
      pageSize: pageSize.value,
    })
    if (res.success) {
      commentList.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error('获取评论失败')
    }
  } catch (error) {
    logger.error('获取评论失败', error)
    ElMessage.error('获取评论失败')
  } finally {
    loading.value = false
  }
}

watch(
  () => props.dealerGoodsStoreId,
  () => {
    currentPage.value = 1
    fetchComments()
  },
)

onMounted(() => {
  fetchComments()
})

const handleSizeChange = (size) => {
  pageSize.value = size
  fetchComments()
}
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchComments()
}
</script>
<template>
  <div class="comment-list-container">
    <div class="comment-scroll-area">
      <el-skeleton v-if="loading" animated :count="5" style="margin: 20px 0">
        <template #template>
          <div style="display: flex; align-items: flex-start; margin-bottom: 24px">
            <el-skeleton-item
              variant="circle"
              style="width: 48px; height: 48px; margin-right: 18px"
            />
            <div style="flex: 1">
              <el-skeleton-item
                variant="text"
                style="width: 120px; height: 18px; margin-bottom: 8px"
              />
              <el-skeleton-item
                variant="text"
                style="width: 80%; height: 16px; margin-bottom: 6px"
              />
              <el-skeleton-item
                variant="text"
                style="width: 60%; height: 16px; margin-bottom: 6px"
              />
              <el-skeleton-item variant="text" style="width: 40%; height: 16px" />
            </div>
          </div>
        </template>
      </el-skeleton>
      <div v-else-if="commentList.length === 0" class="empty-tip">暂无评论</div>
      <div v-else>
        <div v-for="item in commentList" :key="item.evaluateGoodsId" class="comment-item">
          <el-avatar class="avatar" size="large">{{
            item.adminId ? item.adminId.charAt(0).toUpperCase() : '?'
          }}</el-avatar>
          <div class="comment-content">
            <div class="comment-header">
              <span class="admin-id">{{ item.adminId || '匿名' }}</span>
              <span class="comment-time">{{ item.evaluateTime }}</span>
            </div>
            <div class="content">{{ item.evaluateContent }}</div>
            <div v-if="item.imgPathsList && item.imgPathsList.length > 0" class="img-list">
              <el-image
                v-for="(img, idx) in item.imgPathsList"
                :key="idx"
                :src="img"
                style="width: 60px; height: 60px; margin-right: 8px; border-radius: 4px"
                :preview-src-list="item.imgPathsList"
                fit="cover"
                preview-teleported
              />
            </div>
            <div v-if="item.replyEvaluate" class="reply-block">
              <div class="reply-label">商家回复：</div>
              <div class="reply-content">{{ item.replyEvaluate }}</div>
              <div class="reply-time">{{ item.replyTime }}</div>
            </div>
            <el-button type="primary" class="mt-3" size="small" @click="openReplyDialog(item)">
              <template #icon>
                <el-icon><LineMdChatRoundDots /></el-icon>
              </template>
              回复
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 16px; text-align: right"
      />
    </div>

    <el-dialog
      v-model="replyDialogVisible"
      title="回复评论"
      width="30%"
      align-center
      append-to-body
      destroy-on-close
      @close="closeReplyDialog"
    >
      <el-input
        v-model="replyContent"
        type="textarea"
        :rows="4"
        maxlength="200"
        show-word-limit
        placeholder="请输入回复内容"
      />
      <template #footer>
        <el-button @click="closeReplyDialog">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          取消
        </el-button>
        <el-button type="primary" :loading="replyLoading" @click="handleReplySubmit">
          <template #icon>
            <el-icon><LineMdPlus /></el-icon>
          </template>
          提交</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.comment-list-container {
  height: 70vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  position: relative;
  .comment-scroll-area {
    flex: 1;
    overflow-y: auto;
    min-height: 0;
  }
  .empty-tip {
    color: #999;
    text-align: center;
    padding: 40px 0;
  }
  .comment-item {
    display: flex;
    align-items: flex-start;
    padding: 18px 0 18px 0;
    border-bottom: 1px solid #f0f0f0;
    flex: 1;
    .avatar {
      margin-right: 18px;
      background: #e1eaff;
      color: #3a5ed7;
      font-weight: bold;
    }
    .comment-content {
      flex: 1;
      .comment-header {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 6px;
        .admin-id {
          font-weight: 600;
          color: #333;
        }
        .comment-time {
          color: #aaa;
          font-size: 13px;
        }
      }
      .content {
        font-size: 15px;
        color: #222;
        margin-bottom: 8px;
      }
      .img-list {
        display: flex;
        margin-bottom: 8px;
      }
      .reply-block {
        background: #f6f8fa;
        border-radius: 4px;
        padding: 8px 12px;
        margin-top: 6px;
        .reply-label {
          color: #3a5ed7;
          font-size: 13px;
          font-weight: 500;
        }
        .reply-content {
          color: #444;
          margin: 2px 0 0 0;
        }
        .reply-time {
          color: #aaa;
          font-size: 12px;
          margin-top: 2px;
        }
      }
    }
  }
}
.pagination-container {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  width: 100%;
  position: sticky;
  bottom: 0;
  background: #fff;
  z-index: 2;
  box-shadow: 0 -2px 8px 0 rgba(0, 0, 0, 0.02);
}
</style>
